﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OfficeOpenXml;
using WindowsFormsApp1.Models;
using WindowsFormsApp1.Respostories;



namespace WindowsFormsApp1
{
    public partial class QueryForm : Form
    {
        private List<Category> categories = null;
        private List<Data> Datas = null;
        public QueryForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            this.dgvData.AutoGenerateColumns = false;
            this.EnableDoubleBuffer(this.dgvData);

            try
            {
                //获取所有的分类信息
                this.categories = CategoryRepostory.GetCategories();
                Category category1 = new Category
                {
                    Id = "",
                    SlaveId = "所有仓库"
                };
               
                this.categories.Insert(0, category1);

                // 数据源
                this.cbCategory.DataSource = this.categories;
                // 下拉框要显示哪个属性的值
                this.cbCategory.DisplayMember = "SlaveId";
                // 下拉框绑定的value , SelectedValue可以获取此值,通常放表的主键
                this.cbCategory.ValueMember = "SlaveId";

                // 默认选中第1个
                this.cbCategory.SelectedIndex = 0;
                //绑定分类信息到下拉框中
                Datas = DataRepostory.GetData();
                this.dgvData.DataSource = Datas;

            }
            catch (Exception ex)
            {
                MessageBox.Show("加载分类信息失败！" + ex.Message);
            }
        }

        /// <summary>
        /// 分类查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //获取条件
            LoadData();
         
        }

        private void LoadData()
        {
            // 获取条件
            string categorySlaveId = this.cbCategory.SelectedValue.ToString();
            DateTime dtpStarttime = this.dtpStarttime.Value;
            DateTime dtpEndtime = this.dtpEndtime.Value;

            if(dtpStarttime>dtpEndtime)
            {
                MessageBox.Show("起始时间不能大于结束时间！");
                return;
            }

            if(dtpEndtime>=DateTime.Now)
            {
                MessageBox.Show("结束时间不能大于当前时间！");
            }


            // 查询
            try
            {
                this.Datas= DataRepostory.GetData(categorySlaveId, dtpStarttime,dtpEndtime);
                this.dgvData.DataSource = this.Datas;

            }
            catch (Exception ex)
            {
                MessageBox.Show("查询信息失败:" + ex.Message);
            }
        }



        /// <summary>
        /// 在每行头部添加行号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvData_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridView datagridview = sender as DataGridView;
            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(e.RowBounds.Location.X,
            e.RowBounds.Location.Y,
            datagridview.RowHeadersWidth - datagridview.RowHeadersWidth / 2 + 6,
            e.RowBounds.Height);

            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                datagridview.RowHeadersDefaultCellStyle.Font,
                rectangle,
                datagridview.RowHeadersDefaultCellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        /// <summary>
        /// 启动DataGridView双缓存，解决数据量大时出现加载延迟
        /// </summary>
        /// <param name="view"></param>
        public void EnableDoubleBuffer(DataGridView view)
        {
            Type dgvType = view.GetType();
            PropertyInfo pi = dgvType.GetProperty("DoubleBuffered",
                BindingFlags.Instance | BindingFlags.NonPublic);
            pi.SetValue(view, true, null);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //清空条件
            this.dtpEndtime.Value = DateTime.Now;
            this.dtpStarttime.Value = DateTime.Now;
            this.cbCategory.SelectedIndex = 0;
            //重新加载数据
            this.dgvData.DataSource = DataRepostory.GetData();
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
            ExcelPackage package = new ExcelPackage();
            using (package)
            {
                // 添加一个工作表
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
                // 写入列标题
                for (int i = 0; i < dgvData.Columns.Count; i++)
                {
                    worksheet.Cells[1, i + 1].Value = dgvData.Columns[i].HeaderText;
                }
                // 写入数据
                for (int row = 0; row <= dgvData.Rows.Count - 1; row++)
                {
                    for (int col = 0; col < dgvData.Columns.Count; col++)
                    {
                        worksheet.Cells[row + 2, col + 1].Value = dgvData.Rows[row].Cells[col].Value;
                    }
                }
                // 自动调整列宽
                worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
                // 保存文件
                string filePath = "output.xlsx"+DateTime.Now.ToString("yyyyMMddHHmmss")+".xlsx";
                File.WriteAllBytes(filePath, package.GetAsByteArray());
                MessageBox.Show("导出成功！");
            }
        }
    }
    }
    

